//
//  VCSelectTicket.swift
//  AirlineReservation
//
//  Created by Kevin on 2020/1/23.
//  Copyright © 2020 Kevin. All rights reserved.
//

import UIKit

class VCBuyTicket: VCBase {
    
    // 去程航班布局
    private lazy var buyTikcetInfoView:BuyTikcetInfoView = {
        let ui = BuyTikcetInfoView(frame: CGRect(x: MARGIN, y: realHeight, width: S_16_M, height: 180))
        ui.layer.cornerRadius = 5
        ui.layer.masksToBounds = true
        ui.backgroundColor = UIColor.white
        return ui
    }()
    
    // 乘机人
    private lazy var passengerMangerView:PassengerMangerView = {
        let ui = PassengerMangerView()
        ui.backgroundColor = UIColor.white
        ui.frame = CGRect(x: 0, y: buyTikcetInfoView.frame.maxY + MARGIN10, width: SCREEN_WIDTH, height: 60)
        return ui
    }()
    
    // 添加乘机人
    private lazy var passengerMangerBodyView: PassengerMangerBodyView = {
        let ui = PassengerMangerBodyView()
        ui.backgroundColor = UIColor.white
        return ui
    }()
    
    // 联系人
    private lazy var emergenceyContactView: EmergenceyContactView = {
        let ui = EmergenceyContactView()
        ui.backgroundColor = UIColor.white
        ui.frame = CGRect(x: 0, y: passengerMangerView.frame.maxY + MARGIN10, width: SCREEN_WIDTH, height: 320)
        return ui
    }()
    
    // 意外和会员布局
    private lazy var accidentAndMemberView: AccidentAndMemberView = {
        let ui = AccidentAndMemberView()
        ui.backgroundColor = UIColor.white
        ui.frame = CGRect(x: 0, y: emergenceyContactView.frame.maxY + MARGIN10, width: SCREEN_WIDTH, height: 270)
        return ui
    }()
    
    // 提交订单布局
    private lazy var submitTicketInfoView: SubmitTicketInfoView = {
        let ui = SubmitTicketInfoView()
        ui.backgroundColor = COLOR_LIGHT_WHITE2
        ui.frame = CGRect(x: 0, y: SCREEN_HEIGHT - realHeight, width: SCREEN_WIDTH, height: realHeight)
        return ui
    }()
    
    // scrollview
    private lazy var scrollView = UIScrollView()
    // 开通状态
    private var isFaceOn:Bool = false
    private var isFingerOn:Bool = false
    private var isGestureOn:Bool = false
    // 是否退款
    private var isRebackMoeny:Bool = false
    // 航班信息数据
    public var ticketInfo:TicketInfo?
    // 密码支付按钮
    private var payalert: PayAlertView?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        init_set()
        init_view()
        init_data()
        init_event()
    }
}


// MARK: 支付逻辑
extension VCBuyTicket: PayAlertViewDelegate {
    
    // 提交订单到服务器
    private func submitOrder() -> Void {
        self.doPost(api: "save/order", dict: self.orderRequest()) { (dict) in
            if self.isServerSuccess(dict: dict) != 1200 {
                self.show(text: "支付失败，请联系客服")
                return
            }
            let vc = VCTicketSuccess()
            vc.money = self.submitTicketInfoView.money
            self.pushVcHideBottomBar(title: "交易详情", vc: vc)
        }
    }
    
    // 生物认证支付
    private func userBiomericPay() -> Void {
        self.process { (isOK, type) in
            if isOK {
                self.submitOrder()
                return
            }
            self.show(text: "支付失败")
        }
    }
    
    // 手势支付
    private func payUseGesture() -> UIViewController {
        let lock9View = Lock9ViewController()
        lock9View.isTwo = false
        lock9View.isLogin = false
        lock9View.callback = {password,status in
            if status == GestureStatus.SUCCESS {
                self.submitOrder()
            }
        }
        return lock9View
    }
    
    // 使用登录密码支付
    func pay_alert_view_cancle() {
        payalert?.removeFromSuperview()
        }
    
    func pay_alert_view_finish(password: String) {
        if password.count == 0 {
                self.show(text: "密码不能为空")
                return
            }
        if password.count != 6 {
            self.show(text: "密码为6位数")
                return
            }
        payalert?.removeFromSuperview()
            self.submitOrder()
    }
    private func payUseLoginPwd() -> Void {
        UIView.animate(withDuration: 2.0) {
            self.payalert = PayAlertView(frame: self.view.bounds)
            self.payalert?.delegate = self
            self.view.addSubview(self.payalert!)
        }
    }
    
    // 选择支付方式
    private func selectPayMethod() -> Void {
        // 生物认证均为开通，使用登录密码
        if !isGestureOn ,!isFaceOn ,!isFingerOn{
            self.payUseLoginPwd()
            return
        }
        let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
        // 密码支付
        alert.addAction(UIAlertAction(title: "密码支付", style: .default, handler: { (action) in
            self.payUseLoginPwd()
        }))
        // 手势支付
        if isGestureOn {
            alert.addAction(UIAlertAction(title: "手势支付", style: .default, handler: { (action) in
                self.present(self.payUseGesture(), animated: true, completion: nil)
            }))
        }
        // 指纹支付
        if isFingerOn {
            alert.addAction(UIAlertAction(title: "指纹支付", style: .default, handler: { (action) in
                self.userBiomericPay()
            }))
        }
        // 人脸支付
        if isFaceOn {
            alert.addAction(UIAlertAction(title: "人脸支付", style: .default, handler: { (action) in
                self.userBiomericPay()
            }))
        }
        // 取消按钮
        alert.addAction(UIAlertAction(title: "取消", style: .cancel, handler: nil))
        present(alert, animated: true, completion: nil)
    }
}

// MARK: 代码逻辑部分
extension VCBuyTicket {
    
    func requestForID(linkmanid:Int,passengerid:Int,isReturn:Bool = false,isGo:Bool = false) -> NSDictionary {
        let dict = NSMutableDictionary()
        dict.setValue(linkmanid, forKey: "linkmanid")
        dict.setValue(ticketInfo?.food, forKey: "food")
        dict.setValue(ticketInfo?.craft, forKey: "craft")
        dict.setValue(passengerid, forKey: "passengerid")
        dict.setValue(ticketInfo?.mileage, forKey: "mileage")
        dict.setValue(ticketInfo?.miletime, forKey: "miletime")
        dict.setValue(ticketInfo?.cabinname, forKey: "cabinname")
        // 票价
        let showMoney = Int(submitTicketInfoView.money!)!
        let passengerCount = passengerMangerBodyView.passengers!.count
        // 是否返程
        if isReturn {
            dict.setValue(ticketInfo?.endcity, forKey: "city")
            dict.setValue(ticketInfo?.city, forKey: "endcity")
            dict.setValue(ticketInfo?.arrival_time, forKey: "departtime")
            dict.setValue(ticketInfo?.depart_time, forKey: "arrivaltime")
            dict.setValue(ticketInfo?.arrival_date, forKey: "departdate")
            dict.setValue(ticketInfo?.arrival_date, forKey: "arrivaldate")
            dict.setValue(ticketInfo?.depart_terminal, forKey: "arrivalterminal")
            dict.setValue(ticketInfo?.arrival_terminal, forKey: "departterminal")
            dict.setValue(String(describing: (showMoney / passengerCount) / 2), forKey: "ticketprice")
        }else {
            dict.setValue(ticketInfo?.city, forKey: "city")
            dict.setValue(ticketInfo?.endcity, forKey: "endcity")
            dict.setValue(ticketInfo?.depart_date, forKey: "departdate")
            dict.setValue(ticketInfo?.depart_time, forKey: "departtime")
            dict.setValue(ticketInfo?.depart_date, forKey: "arrivaldate")
            dict.setValue(ticketInfo?.arrival_time, forKey: "arrivaltime")
            dict.setValue(ticketInfo?.depart_terminal, forKey: "departterminal")
            dict.setValue(ticketInfo?.arrival_terminal, forKey: "arrivalterminal")
            dict.setValue(String(describing: showMoney / passengerCount), forKey: "ticketprice")
        }
        if isGo {
            dict.setValue(String(describing: (showMoney / passengerCount) / 2), forKey: "ticketprice")
        }
        if let orderid = ticketInfo?.orderid {
            dict.setValue(orderid, forKey: "orderid")
        }
        dict.setValue(ticketInfo?.flight_name, forKey: "flightname")
        dict.setValue(ticketInfo?.flight_number, forKey: "flightnumberid")
        dict.setValue(UserDefaults.standard.string(forKey: SP_USERID), forKey: "userid")
        return dict
    }
    
    // 拼接订单数据
    func orderRequest() -> [NSDictionary] {
        // 联系人
        let linkmanid = emergenceyContactView.accountBean?.linkmanid
        // 乘机人
        var temp = [NSDictionary]()
        for passenger in self.passengerMangerBodyView.passengers! {
            if ((ticketInfo?.arrival_date) == nil) {
                // 去程
                let request = self.requestForID(linkmanid: linkmanid!, passengerid: passenger.passengerid)
                temp.append(request)
            }else {
                // 返程
                let request1 = self.requestForID(linkmanid: linkmanid!, passengerid: passenger.passengerid,isGo: true)
                let request2 = self.requestForID(linkmanid: linkmanid!, passengerid: passenger.passengerid,isReturn: true)
                temp.append(request1)
                temp.append(request2)
            }
        }
        return temp
    }
    
    private func init_event() -> Void {
        // 提交订单按钮
        submitTicketInfoView.complte = {
            // 乘机人是否为空
            guard let passengers = self.passengerMangerBodyView.passengers else {
                self.show(text: "请选择乘机人")
                return
            }
            if passengers.count == 0 {
                self.show(text: "请选择乘机人")
                return
            }
            // 订单支付
            // 本地 生物识别是否开通
            let biometric = UserDefaults.standard.integer(forKey: SP_BIOMETRIC_PAY_PWD)
            if biometric == 1 {
                self.isFingerOn = true
            }
            if biometric == 2 {
                self.isFaceOn = true
            }
            // 本地 手势识别是否开通
            let gesturePwd = UserDefaults.standard.string(forKey: SP_GESTURE_PAY_PWD)
            if gesturePwd != nil {
                self.isGestureOn = true
            }
            // 选择支付的方式
            self.selectPayMethod()
        }
        
        // 添加乘机人按钮
        passengerMangerView.complete = {
            let vc = VCPassenger()
            vc.delegate = self
            vc.isShowOK = true
            vc.isShowCheckBox = true
            self.pushVc(title: "选择乘机人", vc: vc)
        }
        
        // 联系人按钮
        emergenceyContactView.complete = {
            let vc = VCAccount()
            vc.delegate = self
            vc.isNeedAccount = true
            self.pushVc(title: "选择联系人", vc: vc)
        }
        
        // 乘机人删除按钮
        passengerMangerBodyView.complete = {item in
            if var beans = self.passengerMangerBodyView.passengers,beans.count > 0 {
                beans.remove(at: item)
                self.passengerMangerBodyView.passengers = beans
                self.set_passenger_layout(count: beans.count)
                // 更新显示的金额
                self.updateShowMoney(count: beans.count)
                // 关闭意外险
                self.accidentAndMemberView.uiSwitch.isOn = false
            }
        }
    }
    
    // 更新显示的金额
    func updateShowMoney(count:Int) -> Void {
        guard let ticketPrice = ticketInfo?.ticket_price else {
            return
        }
        let moneyInt = Int(ticketPrice)! * count
        // 机票金额
        if ((ticketInfo?.arrival_date) != nil) {
            submitTicketInfoView.money = String(describing: moneyInt * 2)
        }else {
            submitTicketInfoView.money = String(describing: moneyInt)
        }
        // 变更金额
        if let orderprice = ticketInfo?.orderprice {
            let showmoney = Int(submitTicketInfoView.money ?? "0")!
            if orderprice == showmoney {
                submitTicketInfoView.money = "0"
            }else if orderprice > showmoney {
                isRebackMoeny = true
                submitTicketInfoView.money = "0"
            }else {
                submitTicketInfoView.money = String(describing: showmoney - orderprice)
            }
        }
        // 是否开启保险
        accidentAndMemberView.completeSwitch = {isOn in
            let money = Int(self.submitTicketInfoView.money!)
            if money == 0 {
                return
            }
            let extraMoeny = self.passengerMangerBodyView.passengers!.count * 30
            if isOn {
                self.submitTicketInfoView.money = String(describing: money! + extraMoeny )
            }else {
                self.submitTicketInfoView.money = String(describing: money! - extraMoeny )
            }
        }
    }
}

// MARK: 代码不变部分
extension VCBuyTicket: VCPassengerDelegate,VCAccountDelete {
    
    func returnAccount(bean: AccountBean) {
        emergenceyContactView.accountBean = bean
    }
    
    func returnContacts(beans: [UserInfo]) {
        // 关闭意外险
        self.accidentAndMemberView.uiSwitch.isOn = false
        // 改签
        if let orderid = ticketInfo?.orderid {
            if beans.count > 1 {
                self.show(text: "对不起，您每次仅能改签一张票")
                return
            }
            // 校验票乘机人
            let request = NSMutableDictionary()
            request.setValue(orderid, forKey: "orderid")
            // 请求
            self.doPost(api: "valid/order", dict: request) { (dict) in
                // 解析数据
                let result = dict.value(forKey: SP_BODYREQUEST) as! NSDictionary
                let username = result.value(forKey: "username") as! String
                let idnumber = result.value(forKey: "idnumber") as! String
                // 对比选择的乘机人
                if !username.elementsEqual(beans[0].username!) {
                    self.show(text: "您选择的乘机人信息不正确")
                    return
                }
                if !idnumber.elementsEqual(beans[0].idnumber!) {
                    self.show(text: "您选择的乘机人信息不正确.")
                    return
                }
                self.updatePassengerLayout(beans: beans)
            }
        }else {
            updatePassengerLayout(beans: beans)
        }
    }
    
    private func updatePassengerLayout(beans: [UserInfo]) -> Void {
        // 乘机人信息
        passengerMangerBodyView.passengers = beans
        // 重设乘机人布局
        set_passenger_layout(count: beans.count)
        // 更新显示的金额
        updateShowMoney(count: beans.count)
    }
    
    func set_passenger_layout(count: Int) -> Void {
        // 重设乘机人布局
        let bodyY = passengerMangerView.frame.maxY
        let bodyH = CGFloat(count) * MARGIN70 + MARGIN10
        passengerMangerBodyView.frame = CGRect(x: 0, y: bodyY, width: SCREEN_WIDTH, height: bodyH)
        scrollView.addSubview(passengerMangerBodyView)
        
        // 由于添加乘机人 重新设置联系人、意外和会员布局frame
        emergenceyContactView.frame.origin.y = passengerMangerBodyView.frame.maxY + MARGIN10
        accidentAndMemberView.frame.origin.y = emergenceyContactView.frame.maxY + MARGIN10
        // 重新设置 scrollview
        scrollView.addSubview(emergenceyContactView)
        scrollView.contentSize = CGSize(width: SCREEN_WIDTH, height: accidentAndMemberView.frame.maxY + MARGIN80)
    }
    
    private func init_data() -> Void {
        // 机票信息
        buyTikcetInfoView.restTicketInfo = ticketInfo
        // 第一条联系人
        let items = NSMutableDictionary()
        items.setValue(UserDefaults.standard.value(forKey: SP_USERID), forKey: SP_USERID)
        // 请求
        self.doPost(api: "search/linkman", dict: items) { (dict) in
            if self.isServerSuccess(dict: dict) != 1200 {
                return
            }
            var temp = [AccountBean]()
            let arrs = dict.value(forKey: SP_BODYREQUEST) as! NSArray
            for item in arrs {
                let info = AccountBean(dict: item as! [String : Any])
                temp.append(info)
            }
            self.emergenceyContactView.accountBean = temp[0]
        }
        // 修改支付文本
        if ticketInfo?.orderid != nil {
            self.submitTicketInfoView.submitBtnText = "确认变更"
        }
    }
    
    private func init_view() -> Void {
        scrollView.addSubview(backgroundImg)
        scrollView.addSubview(buyTikcetInfoView)
        scrollView.addSubview(passengerMangerView)
        scrollView.addSubview(emergenceyContactView)
        scrollView.addSubview(accidentAndMemberView)
        // 添加到 scrollview
        view.addSubview(scrollView)
        scrollView.contentSize = CGSize(width: SCREEN_WIDTH, height: accidentAndMemberView.frame.maxY + MARGIN80)
        // 提交订单布局
        view.addSubview(submitTicketInfoView)
    }
    
    private func init_set() -> Void {
        title = "添加乘机信息"
        scrollView.delegate = self
        scrollView.frame = view.frame
        scrollView.showsVerticalScrollIndicator = false
        scrollView.contentInset = UIEdgeInsets(top: -realHeight, left: 0, bottom: 0, right: 0)
    }
}

extension VCBuyTicket:UIScrollViewDelegate {
    
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        scrollView.endEditing(true)
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if scrollView.contentOffset.y > 20 {
            title = ""
        }else {
            title = "添加乘机信息"
        }
    }
}
